package com.smile.filter;

import com.smile.helper.TokenHelper;
import com.smile.util.SpringBeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;
import com.smile.util.TokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * JWT令牌过滤器类
 * 用于拦截HTTP请求，验证JWT令牌并设置Spring Security的认证信息
 */
public class JwtTokenFilter extends GenericFilterBean {


    /**
     * 执行过滤器逻辑
     * 从请求中提取JWT令牌，验证令牌有效性，并设置Spring Security的认证上下文
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取token
        String token = TokenUtil.getTokenForAuthorization(httpServletRequest);

        if (Objects.isNull(token)) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        TokenHelper tokenHelper = SpringBeanUtil.getBean("tokenHelper");

        if (Objects.nonNull(tokenHelper)) {
            String username = tokenHelper.getUsernameFromToken(token);
            if (StringUtils.isNoneBlank(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = tokenHelper.getUserDetailsFromUsername(username);

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                //将获取的数据封装到Authentication对象中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(httpServletRequest, servletResponse);
    }
}
